package 每日一题;

import org.junit.Test;

public class 秘钥格式化 {

    //别人家的写法
    public String licenseKeyFormatting1(String s, int k) {
        StringBuffer sb = new StringBuffer(s.replaceAll("-", "").toUpperCase());
        for (int i = sb.length() - k; i > 0; i -= k) {
            sb.insert(i, '-');
        }
        return sb.toString();
    }

    public String licenseKeyFormatting(String s, int k) {
        String[] split = s.split("-");
        StringBuilder builder = new StringBuilder();
        for (String s1 : split) {
            //转换成大写字母
            builder.append(s1.toUpperCase());
        }
        if (builder.length()==0)
            return "";
        //第一个字符的长度
        int len = builder.length() % k;
        int num = builder.length() / k;
        StringBuilder res = new StringBuilder();
        if (len==0){
            for (int i = 0; i < num; i++) {
                String substring = builder.substring(i * k, (i + 1) * k);
                res.append(substring).append("-");
            }
        }
        else{
            String substring = builder.substring(0, len);
            res.append(substring).append("-");
            for (int i = 0; i < num; i++) {
                String s1 = builder.substring(len + i * k, len + (i + 1) * k);
                res.append(s1).append("-");
            }
        }
        res.deleteCharAt(res.length()-1);
        return res.toString();
    }
    @Test
    public void test(){
        String s = "---";
        String[] split = s.split("-");
        StringBuilder builder = new StringBuilder();
        for (String s1 : split) {
            builder.append(s1);
        }
        System.out.println(builder);
        System.out.println(builder.length());
    }

}
